/**
 * 路由工具函数
 * 处理qiankun环境下的路由配置
 */
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

/**
 * 获取基础路径
 * @returns {string} 基础路径
 */
export function getBasePath() {
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    return '/exp/'
  }
  return '/'
}

/**
 * 获取完整路径
 * @param {string} path 相对路径
 * @returns {string} 完整路径
 */
export function getFullPath(path) {
  const basePath = getBasePath()
  return `${basePath}${path}`.replace(/\/+/g, '/')
}

/**
 * 检查是否在qiankun环境中
 * @returns {boolean} 是否在qiankun环境中
 */
export function isQiankun() {
  return qiankunWindow.__POWERED_BY_QIANKUN__
}

/**
 * 获取当前路由信息
 * @returns {Object} 路由信息
 */
export function getCurrentRouteInfo() {
  return {
    pathname: window.location.pathname,
    search: window.location.search,
    hash: window.location.hash,
    isQiankun: isQiankun(),
    basePath: getBasePath(),
    activeRule: '/exp'
  }
}


/**
 * 获取路由配置
 * @returns {Object} 路由配置
 */
export function getRouterConfig() {
  return {
    base: getBasePath(),
    mode: 'history',
    routes: [
      {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: '/about',
        name: 'About',
        component: () => import('@/views/About.vue'),
        meta: { title: '关于' }
      },
      {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue'),
        meta: { title: '404' }
      }
    ]
  }
}

/**
 * 路由守卫配置
 * @param {Object} router 路由实例
 */
export function setupRouterGuards(router) {
  router.beforeEach((to, from, next) => {
    console.log('[路由工具] 路由跳转:', to.path)
    console.log('[路由工具] 运行环境:', isQiankun() ? 'qiankun' : '独立')
    console.log('[路由工具] 基础路径:', getBasePath())
    
    // 设置页面标题
    if (to.meta.title) {
      document.title = to.meta.title
    }
    
    next()
  })
} 